import React, { useState, useEffect } from 'react';
import { Card, Button, Space, Tag, Modal, message, Form, Input, Select, Row, Col } from 'antd';
import { 
  PlusOutlined, 
  SearchOutlined, 
  ReloadOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  ExclamationCircleOutlined,
  SettingOutlined,
  UserOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { CustomTable } from '../../g-component/CustomTable';
import { UserGroup } from '../../g-types/userGroup';
import { UserGroupApi } from './server';
import './index.less';

const { confirm } = Modal;
const { Option } = Select;
const { TextArea } = Input;

/**
 * 用户组状态标签
 */
const GroupStatusTag: React.FC<{ status?: number }> = ({ status }) => {
  if (status === 0) {
    return <Tag color="error">禁用</Tag>;
  }
  return <Tag color="success">启用</Tag>;
};

// 搜索条件接口
interface SearchParams {
  page?: number;
  pageSize?: number;
  keyword?: string;
  name?: string;
  code?: string;
  status?: number;
  [key: string]: string | number | undefined;
}

// 搜索配置接口
interface SearchConfigType {
  name: boolean;
  code: boolean;
  status: boolean;
}

/**
 * 用户组列表内容组件 - 不包含布局
 */
export const UserGroupContent: React.FC = () => {
  // 用户组列表数据
  const [groupList, setGroupList] = useState<UserGroup[]>([]);
  // 加载状态
  const [loading, setLoading] = useState<boolean>(false);
  // 分页信息
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  
  // 搜索表单
  const [searchForm] = Form.useForm();
  
  // 编辑用户组的表单
  const [editForm] = Form.useForm();
  
  // 是否显示编辑Modal
  const [editModalVisible, setEditModalVisible] = useState<boolean>(false);
  
  // 是否显示搜索项配置Modal
  const [searchConfigVisible, setSearchConfigVisible] = useState<boolean>(false);
  
  // 当前编辑的用户组
  const [currentGroup, setCurrentGroup] = useState<UserGroup | null>(null);

  // 搜索条件
  const [searchParams, setSearchParams] = useState<SearchParams>({});

  // 搜索字段显示配置
  const [searchConfig, setSearchConfig] = useState<SearchConfigType>({
    name: true,
    code: true,
    status: true,
  });

  // 获取用户组列表
  const fetchGroupList = async (page = pagination.current, pageSize = pagination.pageSize, params = searchParams) => {
    try {
      setLoading(true);
      const result = await UserGroupApi.getUserGroupList({
        page,
        pageSize,
        ...params,
      });
      setGroupList(result.list);
      setPagination({
        ...pagination,
        current: page,
        total: result.total,
      });
    } catch (error) {
      console.error('获取用户组列表失败', error);
      message.error('获取用户组列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载数据
  useEffect(() => {
    fetchGroupList();
  }, []);

  // 处理表格变更
  const handleTableChange = (page: number, pageSize?: number) => {
    fetchGroupList(page, pageSize);
  };

  // 处理搜索
  const handleSearch = (values: SearchParams) => {
    // 过滤掉空值
    const params = Object.keys(values).reduce((result, key) => {
      const k = key as keyof SearchParams;
      if (values[k] !== undefined && values[k] !== null && values[k] !== '') {
        result[k] = values[k];
      }
      return result;
    }, {} as SearchParams);
    
    setSearchParams(params);
    fetchGroupList(1, pagination.pageSize, params);
  };

  // 重置搜索
  const handleResetSearch = () => {
    searchForm.resetFields();
    setSearchParams({});
    fetchGroupList(1, pagination.pageSize, {});
  };

  // 处理添加用户组
  const handleAddGroup = () => {
    setCurrentGroup(null);
    editForm.resetFields();
    setEditModalVisible(true);
  };

  // 处理编辑用户组
  const handleEditGroup = (group: UserGroup) => {
    setCurrentGroup(group);
    editForm.setFieldsValue({
      name: group.name,
      code: group.code,
      description: group.description,
      status: group.status,
    });
    setEditModalVisible(true);
  };

  // 处理删除用户组
  const handleDeleteGroup = (group: UserGroup) => {
    confirm({
      title: '确定要删除此用户组吗?',
      icon: <ExclamationCircleOutlined />,
      content: '删除后无法恢复',
      onOk: async () => {
        try {
          await UserGroupApi.deleteUserGroup(group.id);
          message.success('删除成功');
          fetchGroupList();
        } catch (error) {
          console.error('删除用户组失败', error);
          message.error('删除用户组失败');
        }
      },
    });
  };

  // 保存用户组信息
  const handleSaveGroup = async () => {
    try {
      const values = await editForm.validateFields();
      if (currentGroup) {
        // 编辑用户组
        await UserGroupApi.updateUserGroup({
          id: currentGroup.id,
          ...values,
        });
        message.success('更新用户组成功');
      } else {
        // 新增用户组
        await UserGroupApi.createUserGroup(values);
        message.success('创建用户组成功');
      }
      setEditModalVisible(false);
      fetchGroupList();
    } catch (error) {
      console.error('保存用户组失败', error);
      message.error('保存用户组失败');
    }
  };

  // 保存搜索项配置
  const handleSaveSearchConfig = (newConfig: SearchConfigType) => {
    setSearchConfig(newConfig);
    setSearchConfigVisible(false);
  };

  // 管理用户组成员
  const handleManageMembers = (group: UserGroup) => {
    message.info(`功能开发中: 管理"${group.name}"的成员`);
  };

  // 表格列定义
  const columns: ColumnsType<UserGroup> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
    },
    {
      title: '编码',
      dataIndex: 'code',
      key: 'code',
      width: 120,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '成员数量',
      dataIndex: 'userCount',
      key: 'userCount',
      width: 100,
      render: (userCount) => userCount || 0,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status) => <GroupStatusTag status={status} />,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 120,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="link" 
            icon={<UserOutlined />} 
            onClick={() => handleManageMembers(record)}
            title="管理成员"
          >
            成员
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleEditGroup(record)}
            title="编辑"
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />} 
            onClick={() => handleDeleteGroup(record)}
            title="删除"
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 搜索配置Modal内容
  const searchConfigContent = (
    <Form 
      layout="vertical"
      initialValues={searchConfig}
      onFinish={handleSaveSearchConfig}
    >
      <Row gutter={24}>
        {Object.keys(searchConfig).map((key) => (
          <Col span={8} key={key}>
            <Form.Item
              name={key}
              label={(() => {
                switch(key) {
                  case 'name': return '名称';
                  case 'code': return '编码';
                  case 'status': return '状态';
                  default: return key;
                }
              })()}
              valuePropName="checked"
            >
              <Select>
                <Option value={true}>显示</Option>
                <Option value={false}>隐藏</Option>
              </Select>
            </Form.Item>
          </Col>
        ))}
      </Row>
      <Form.Item>
        <Button type="primary" htmlType="submit">
          保存配置
        </Button>
      </Form.Item>
    </Form>
  );

  // 搜索表单内容
  const searchFormContent = (
    <Form
      form={searchForm}
      name="searchForm"
      layout="inline"
      onFinish={handleSearch}
      style={{ marginBottom: 16 }}
    >
      <Row gutter={[16, 16]} style={{ width: '100%' }}>
        {searchConfig.name && (
          <Col span={6}>
            <Form.Item name="name" label="名称">
              <Input placeholder="请输入名称" allowClear />
            </Form.Item>
          </Col>
        )}
        {searchConfig.code && (
          <Col span={6}>
            <Form.Item name="code" label="编码">
              <Input placeholder="请输入编码" allowClear />
            </Form.Item>
          </Col>
        )}
        {searchConfig.status && (
          <Col span={6}>
            <Form.Item name="status" label="状态">
              <Select placeholder="请选择状态" allowClear>
                <Option value={1}>启用</Option>
                <Option value={0}>禁用</Option>
              </Select>
            </Form.Item>
          </Col>
        )}
        <Col span={6} style={{ textAlign: 'right', marginLeft: 'auto' }}>
          <Space>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              搜索
            </Button>
            <Button icon={<ReloadOutlined />} onClick={handleResetSearch}>
              重置
            </Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAddGroup}>
              新建
            </Button>
            <Button icon={<SettingOutlined />} onClick={() => setSearchConfigVisible(true)}>
              配置
            </Button>
          </Space>
        </Col>
      </Row>
    </Form>
  );
  
  return (
    <div className="user-group-container">
      <Card 
        title="用户组管理" 
        bordered={false}
        className="user-group-card"
      >
        {searchFormContent}
        
        <CustomTable
          loading={loading}
          dataSource={groupList}
          columns={columns}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            onChange: handleTableChange,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
          }}
          rowKey="id"
        />
      </Card>
      
      {/* 编辑用户组对话框 */}
      <Modal
        title={currentGroup ? '编辑用户组' : '新增用户组'}
        open={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setEditModalVisible(false)}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={handleSaveGroup}>
            保存
          </Button>,
        ]}
        maskClosable={false}
        destroyOnClose
      >
        <Form
          form={editForm}
          layout="vertical"
          name="editForm"
        >
          <Form.Item
            name="name"
            label="名称"
            rules={[
              { required: true, message: '请输入用户组名称' },
              { max: 50, message: '名称最多50个字符' },
            ]}
          >
            <Input placeholder="请输入用户组名称" />
          </Form.Item>
          <Form.Item
            name="code"
            label="编码"
            rules={[
              { required: true, message: '请输入用户组编码' },
              { max: 30, message: '编码最多30个字符' },
              { pattern: /^[a-zA-Z0-9_]+$/, message: '编码只能包含字母、数字和下划线' },
            ]}
          >
            <Input placeholder="请输入用户组编码" />
          </Form.Item>
          <Form.Item
            name="description"
            label="描述"
            rules={[
              { max: 200, message: '描述最多200个字符' },
            ]}
          >
            <TextArea placeholder="请输入用户组描述" rows={4} />
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            initialValue={1}
          >
            <Select placeholder="请选择状态">
              <Option value={1}>启用</Option>
              <Option value={0}>禁用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
      
      {/* 搜索配置对话框 */}
      <Modal
        title="搜索项配置"
        open={searchConfigVisible}
        onCancel={() => setSearchConfigVisible(false)}
        footer={null}
        destroyOnClose
      >
        {searchConfigContent}
      </Modal>
    </div>
  );
}; 